package aspects;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import annotations.Repeat;
import annotations.Skip;

public class ExceptionHandlingHelper {
	
	public static boolean shouldHandleException(Object annotation, Exception e){
		Repeat anno = null;
		Skip skip = null;
		Class[] accept = null;
		Class[] ignore = null;
		if (annotation instanceof Repeat){
			anno = (Repeat)annotation;
			accept = anno.include();
			ignore = anno.exclude();
		}
		else if (annotation instanceof Skip){
			skip = (Skip)annotation;
			accept = skip.include();
			ignore = skip.exclude();
		}

		boolean shouldProceed = true;
		
		if(accept.length > 0 && ignore.length>0)
			throw new RuntimeException("accept and ignore cannot be declared at the same time");
		if(accept.length > 0)
		{
			System.out.println("Jest Parametr Accept");
			shouldProceed = false;
			for (Class<?> clazz : accept)
			{
				if(clazz.equals(e.getClass()))
				{
					shouldProceed = true;
					break;
				}
			}
		}
		if(ignore.length > 0)
		{
			System.out.println("Jest Parametr Ignore");
			shouldProceed = true;
			for (Class<?> clazz : ignore)
			{
				if(clazz.equals(e.getClass()))
				{
					shouldProceed = false;
					break;
				}
			}
		}
		return shouldProceed;			
	}
	
	@SuppressWarnings("unchecked")
	public static Boolean invokeSelfHandling(Class myHandlingClass) {
		Object myHandlingObject = new Object();
		Class noparams[] = {};
		Method method;
		Boolean result = false;
		
		try {
			myHandlingObject = myHandlingClass.newInstance();
			method = myHandlingClass.getDeclaredMethod("selfHandlingMethod", noparams);
			result = (Boolean) method.invoke(myHandlingObject);

		} catch (InstantiationException | IllegalAccessException | NoSuchMethodException 
				| SecurityException | IllegalArgumentException | InvocationTargetException e1) {
			e1.printStackTrace();
		}
		return result;
	}

}
